<!-- 查询所有列表的中间件 -->
<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogVisible"
    width="70%"
    append-to-body
  >
    <!-- 搜索表单，动态渲染搜索条件 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true">
      <el-form-item v-for="(item, index) in searchItems" :key="index" :label="item.label">
        <el-input
          v-if="item.type === 'input'"
          v-model="queryParams[item.field]"
          :placeholder="item.placeholder || '请输入' + item.label"
          clearable
          @keyup.enter.native="handleSearch"
        />
        <el-select
          v-else-if="item.type === 'select'"
          v-model="queryParams[item.field]"
          :placeholder="item.placeholder || '请选择' + item.label"
          clearable
          style="width: 180px"
        >
          <el-option
            v-for="option in item.options"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
        <el-date-picker
          v-else-if="item.type === 'date'"
          v-model="queryParams[item.field]"
          type="date"
          value-format="yyyy-MM-dd"
          :placeholder="item.placeholder || '请选择' + item.label"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格，根据传入的列配置动态渲染 -->
    <el-table
      v-loading="loading"
      :data="dataList"
      @row-click="handleRowClick"
      highlight-current-row
      border
      :height="tableHeight"
    >
      <el-table-column type="index" width="50" />
      <el-table-column
        v-for="(column, index) in columns"
        :key="index"
        :prop="column.prop"
        :label="column.label"
        :width="column.width"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <span v-if="column.formatter" v-html="column.formatter(scope.row)"></span>
          <span v-else-if="scope.row[column.prop] !== undefined && scope.row[column.prop] !== null">{{ scope.row[column.prop] }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
    </el-table>



    <!-- 分页控件 -->
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageInfo.current"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="pageInfo.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>

    <!-- 对话框底部操作按钮 -->
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleCancel">取 消</el-button>
      <el-button type="primary" @click="confirmSelection" :disabled="!selectedRow">确 认</el-button>
    </div>
  </el-dialog>
</template>

<script>
// TODO: 后期需要引入相关API接口
// import { listSuppliers } from "@/api/basic/suppliers";
// import { listTemplates } from "@/api/qc/templates";
// import { listSourceDocs } from "@/api/qc/sourceDocs";

export default {
  name: "CommonSelector",
  props: {
    // 对话框标题
    title: {
      type: String,
      default: "选择"
    },
    // 是否显示对话框
    visible: {
      type: Boolean,
      default: false
    },
    // 搜索条件配置
    searchItems: {
      type: Array,
      default: () => []
    },
    // 表格列配置
    columns: {
      type: Array,
      default: () => []
    },
    // 查询初始参数
    initQuery: {
      type: Object,
      default: () => ({})
    },
    // 加载数据的方法
    fetchDataMethod: {
      type: Function,
      default: null
    },
    // 可选项中的数据
    dataOptions: {
      type: Array,
      default: null
    },
    // 是否显示调试信息
    showDebug: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      // 查询参数
      queryParams: {},
      // 数据列表
      dataList: [],
      // 加载状态
      loading: false,
      // 选中的行
      selectedRow: null,
      // 表格高度
      tableHeight: 350,
      // 分页信息
      pageInfo: {
        current: 1,
        size: 10
      },
      // 总数据量
      total: 0
    };
  },
  computed: {
    dialogVisible: {
      get() {
        return this.visible;
      },
      set(val) {
        this.$emit("update:visible", val);
      }
    },
    // 根据查询条件过滤数据，并应用分页
    // filteredDataList() {
    //   let filteredData = [...this.dataList];

    //   // 根据查询参数过滤数据
    //   if (this.queryParams && Object.keys(this.queryParams).length > 0) {
    //     Object.keys(this.queryParams).forEach(key => {
    //       const value = this.queryParams[key];
    //       if (value !== undefined && value !== null && value !== '') {
    //         filteredData = filteredData.filter(item => {
    //           // 处理字段名称不一致的情况
    //           const itemValue = item[key];
    //           if (itemValue === undefined || itemValue === null) return false;

    //           if (typeof itemValue === 'string') {
    //             return itemValue.toLowerCase().includes(String(value).toLowerCase());
    //           }
    //           return String(itemValue) === String(value);
    //         });
    //       }
    //     });
    //   }

    //   // 计算分页
    //   const startIndex = (this.pageInfo.current - 1) * this.pageInfo.size;
    //   const endIndex = startIndex + this.pageInfo.size;

    //   return filteredData.slice(startIndex, endIndex);
    // },
    // // 过滤后的总数据量
    // filteredTotal() {
    //   let filteredData = [...this.dataList];

    //   // 根据查询参数过滤数据
    //   if (this.queryParams && Object.keys(this.queryParams).length > 0) {
    //     Object.keys(this.queryParams).forEach(key => {
    //       const value = this.queryParams[key];
    //       if (value !== undefined && value !== null && value !== '') {
    //         filteredData = filteredData.filter(item => {
    //           // 处理字段名称不一致的情况
    //           const itemValue = item[key];
    //           if (itemValue === undefined || itemValue === null) return false;

    //           if (typeof itemValue === 'string') {
    //             return itemValue.toLowerCase().includes(String(value).toLowerCase());
    //           }
    //           return String(itemValue) === String(value);
    //         });
    //       }
    //     });
    //   }

    //   return filteredData.length;
    // }
  },
  watch: {
    visible(val) {
      if (val) {
        // 初始化查询参数
        this.initQueryParams();
        // 加载数据
        this.fetchData();
        // 重置分页
        this.pageInfo.current = 1;
        // 清除选中行
        this.selectedRow = null;
      } else {
        // 对话框关闭时清除选中行
        this.selectedRow = null;
      }
    },
    // 监听外部传入的数据选项变化
    dataOptions: {
      handler(val) {
        if (val && Array.isArray(val) && val.length > 0) {
          console.log("dataOptions changed:", val);
          this.dataList = [...val];
        } else {
          this.dataList = [];
        }
      },
      immediate: true,
      deep: true
    }
  },
  mounted() {
    if (this.dataOptions && this.dataOptions.length > 0) {
      this.dataList = [...this.dataOptions];
    }
  },
  created() {
    this.initQueryParams();
  },
  methods: {
    // 初始化查询参数
    initQueryParams() {
      // 合并初始查询参数
      this.queryParams = { ...this.initQuery };
    },
    // 加载数据
    fetchData() {
      // 如果有数据选项，直接使用
      if (this.dataOptions && Array.isArray(this.dataOptions) && this.dataOptions.length > 0) {
        console.log("fetchData using dataOptions:", this.dataOptions);
        this.dataList = [...this.dataOptions];
        return;
      }

      // 如果有提供数据获取方法，则调用
      if (this.fetchDataMethod) {
        this.loading = true;
        this.fetchDataMethod({
          ...this.queryParams,
          pageNum: this.pageInfo.current,
          pageSize: this.pageInfo.size
        })
          .then(response => {
            // 处理直接返回数组或包含rows属性的两种情况
          if (response && response.rows) {
            this.dataList = response.rows;
            this.total = response.total;
          } else if (Array.isArray(response)) {
            this.dataList = response;
            this.total = response.length;
          } else {
            this.dataList = [];
            this.total = 0;
          }
          })
          .catch(() => {
            this.dataList = [];
            this.total = 0;
          })
          .finally(() => {
            this.loading = false;
          });
      } else {
        // 无数据获取方法和数据选项，使用空数组
        console.log("No fetchDataMethod or dataOptions available");
        this.dataList = [];
      }
    },
    // 搜索
    handleSearch() {
      this.pageInfo.current = 1;
      if (this.fetchDataMethod) {
        this.fetchData();
      }
      // 本地搜索模式下，不需要重新加载，computed属性会自动过滤
    },
    // 重置查询
    resetQuery() {
      this.initQueryParams();
      this.pageInfo.current = 1;
      if (this.fetchDataMethod) {
        this.fetchData();
      }
    },
    // 行点击事件
    handleRowClick(row) {
      this.selectedRow = row;
    },
    // 取消选择
    handleCancel() {
      this.dialogVisible = false;
      this.$emit("cancel");
    },
    // 确认选择
    confirmSelection() {
      if (this.selectedRow) {
        this.$emit("select", this.selectedRow);
        this.dialogVisible = false;
      } else {
        this.$message.warning("请选择一条数据");
      }
    },
    // 处理每页显示数量变化
    handleSizeChange(val) {
      this.pageInfo.size = val;
      this.fetchData();
    },
    // 处理页码变化
    handleCurrentChange(val) {
      this.pageInfo.current = val;
      this.fetchData();
    }
  }
};
</script>

<style scoped>
.dialog-footer {
  margin-top: 10px;
}

.pagination-container {
  text-align: center;
  margin-top: 15px;
}
</style>
